package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器
@Component //他不属于三层所以他是@Controller
public class LoginCheckInterceptor implements HandlerInterceptor {



    @Override //访问拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session中的对象
        HttpSession session = request.getSession();
        Employee attribute = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        // 未登录 拦截
        if (attribute==null){
            // 设置结果返回
            ResultInfo notlogin = ResultInfo.error("NOTLOGIN");
            // 手动转成json
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(notlogin);
            // 通过json反映
            response.setContentType("application/json;charset=utf-8"); //告诉前端响应的类型
            response.getWriter().write(s); // 把json 对象响应回去
            //拦截
            return false;
        }
        // 放行
        // 在通过校验后我们把Employee存入到线程中
        EmployeeHolder.set(attribute);
        return true;

    }
  @Override // 再删除当前线程里的对象
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
EmployeeHolder.remove();
    }
}
